"""
DOCSTRING
"""

import ConfigParser

class SectionError(RuntimeError):
    pass

class OptionError(RuntimeError):
    pass

class Configuration(object):

    class ConfigurationSection(object):
        def __init__(self, config, section):
            self.__config = config
            self.__section = section

        def set(self, name, value):
            self.__config.set(self.__section, name, value)
            return value

        def __getattr__(self, name):
            if self.__config.has_option(self.__section, name):
                return self.__config.get(self.__section, name)
            raise OptionError, "%s.%s does not exist" % (self.__section, name)

    def __init__(self, configFile = None, default = None):
        if default is None:
            default = {}

        self.__config = ConfigParser.RawConfigParser()

        if configFile is None:
            return

        self.configFile = configFile

        import os
        if os.path.exists(configFile):
            with open(configFile, 'rb') as cffp:
                self.__config.readfp(cffp)

        self.__writeDefault(default)

        self.saveConfig()

    def saveConfig(self):
        """
        """
        with open(self.configFile, 'wb') as cffp:
            self.__config.write(cffp)

    def addSection(self, section):
        """
        """
        if not self.__config.has_section(section):
            self.__config.add_section(section)

    def addValues(self, section, values):
        """
        """
        for name, value in values.iteritems():
            self.addValue(section, name, value)

    def addValue(self, section, name, value):
        """
        """
        self.addSection(section)
        if not self.__config.has_option(section, name):
            self.__config.set(section, name, value)

        return self.__config.get(section, name)

    def __writeDefault(self, default):
        """
        """
        for section, values in default.iteritems():
            self.addValues(section, values)

    def __getattr__(self, name):
        """
        """
        if self.__config.has_section(name):
            return Configuration.ConfigurationSection(self.__config, name)
        raise SectionError, "%s does not exist" % name